import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;

import org.w3c.dom.*;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException; 

import javax.imageio.ImageIO;
import javax.swing.*;

public class LastFMContentGrabber implements Runnable {
	private String artist1, track1,album1;
    private ContentSelector CS;
    private int mode, box;

    public LastFMContentGrabber(ContentSelector content, String artist, String song, String album, int Mode, int Box) {
        artist1 = artist;
        track1 = song;
        album1=album;
        CS = content;
        mode = Mode;
        box = Box;
    }
    
    public void run() {
        switch(mode){
        case 0:
        	CS.content[box].setText(getShoutsString(artist1, track1));
        	break;
        case 1:
        	CS.content[box].setText(getArtistInfoString(artist1));
        	break;
        case 2:
        	CS.content[box].setText(getAlbumInfoString(artist1,album1));
        	break;
        case 3: CS.updateAlbum(getAlbumArt(artist1,album1));
        	
        	break;
        }
    }
    
    
	// Main method is only used to test the class
	public static void main(String[] args) {
		String artist = "Rick Astley";
		String track = "Never Gonna Give You Up";
		if(args.length>1) {
			artist = args[0];
			track = args[1];
		}
		//LastFMContentGrabber grabber = new LastFMContentGrabber();
		//System.out.println(grabber.getShoutsString(artist, track));
		
	}//end of main
	
	//Retrieves comments xml file from last.fm and constructs a string from it
	public String getShoutsString(String artist, String track) {
		String result = "";
		try {
			DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
			String xml_uri = "http://ws.audioscrobbler.com/2.0/?method=track.getshouts&artist=" + artist + "&track=" + track + "&api_key=1798ac371aad9cf8faef329514d55820";
			Document xml_file = docBuilder.parse(xml_uri);

			xml_file.getDocumentElement().normalize();
			NodeList shouts = xml_file.getElementsByTagName("shout");
			if(shouts.getLength()==0)
				result = "Sorry, there are no comments to display about this track\n";
			else
			{
				for(int i=0; i<shouts.getLength() ; i++) {
					NodeList current_shout = shouts.item(i).getChildNodes();
					for(int j=0;j<current_shout.getLength();j++) {
						Node tag = current_shout.item(j);
						if(tag.getNodeName()=="body") 
							result += tag.getTextContent() + "\n";
						else if(tag.getNodeName()=="author")
							result += "    - posted by " + tag.getTextContent();
						else if(tag.getNodeName()=="date") {
							result += " on " + tag.getTextContent().substring(5, 16) + "\n";
						}
					}
					result += "\n";
				}						
			}		
		}
		catch (IOException io_error) {
			result = "Unable to retrieve comments about this track\n";
		}
		catch (SAXParseException err) {
			System.out.println("** Parsing error" + ", line " + err.getLineNumber() + ", uri " + err.getSystemId());
			System.out.println(" " + err.getMessage());
		}
		catch (SAXException e) {
			Exception x = e.getException();
			((x==null) ? e : x).printStackTrace();
		}
		catch (Throwable t) {
			t.printStackTrace();
		}

		result = result.replaceAll("&quot;", "\"");
		return result;
	}//end of getShoutsString
	
	//Retrieves comments as a string and puts it inside a JTextArea
	public JTextArea getShouts(String artist, String track) {
		JTextArea textArea = new JTextArea(30, 50);
		textArea.setEditable(false);
		textArea.append(getShoutsString(artist, track));
		
		return textArea;
	}//end of getShouts
	
	//Retrieves artist info xml file from last.fm, extracts biography and constructs a string from it
	public String getArtistInfoString(String artist) {
		String result = "";
		try {
			DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
			String xml_uri = "http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=" + artist + "&api_key=1798ac371aad9cf8faef329514d55820";
			Document xml_file = docBuilder.parse(xml_uri);
			
			xml_file.getDocumentElement().normalize();
			
			NodeList bio = xml_file.getElementsByTagName("bio").item(0).getChildNodes();
			for(int i=0; i<bio.getLength() ; i++) {
				if(bio.item(i).getNodeName()=="content") 
					result = bio.item(i).getTextContent();
			}
			result = result.substring(0, result.indexOf("User-contributed text"));
		}
		catch (IOException io_error) {
			result = "Unable to retrieve any information about this track\n";
		}
		catch (SAXParseException err) {
			System.out.println("** Parsing error" + ", line " + err.getLineNumber() + ", uri " + err.getSystemId());
			System.out.println(" " + err.getMessage());
		}
		catch (SAXException e) {
			Exception x = e.getException();
			((x==null) ? e : x).printStackTrace();
		}
		catch (Throwable t) {
			t.printStackTrace();
		}
		
		result = CleanupText(result);
		return result;
	}//end of getArtistInfoString
	
	//Retrieves artist biography as a string and puts it inside a JTextArea
	public JTextArea getArtistInfo(String artist) {
		JTextArea textArea = new JTextArea(30, 50);
		textArea.setEditable(false);
		textArea.append(getArtistInfoString(artist));
		
		return textArea;
	}//end of getArtistInfo
	
	//Removes HTML tags and &quot; from a String
	private String CleanupText(String text) {
		String output = "";
		boolean writing = true;
		for(int i=0;i<text.length();i++) {
			if(text.charAt(i)=='<') writing = false;
			if(writing) output += text.charAt(i);
			if(text.charAt(i)=='>') writing = true;
		}
		output = output.replaceAll("&quot;", "\"");
		return output;
	}//end of CleanupText
	
	//Retrieves artist info xml file from last.fm, extracts biography and constructs a string from it
	public String getAlbumArtPath(String artist, String album) {
		String result = "";
		try {
			DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
			String xml_uri = "http://ws.audioscrobbler.com/2.0/?method=album.getinfo&artist=" + artist + "&album=" + album + "&api_key=1798ac371aad9cf8faef329514d55820";
			Document xml_file = docBuilder.parse(xml_uri);
			xml_file.getDocumentElement().normalize();
			
			NodeList images = xml_file.getElementsByTagName("image");
			if (images.getLength()>0) result = images.item(images.getLength()-1).getTextContent();
		}
		catch (IOException io_error) {
			result = "Unable to retrieve any information about this track\n";
		}
		catch (SAXParseException err) {
			System.out.println("** Parsing error" + ", line " + err.getLineNumber() + ", uri " + err.getSystemId());
			System.out.println(" " + err.getMessage());
		}
		catch (SAXException e) {
			Exception x = e.getException();
			((x==null) ? e : x).printStackTrace();
		}
		catch (Throwable t) {
			t.printStackTrace();
		}
		
		return result;
	}//end of getAlbumArtPath
	
	//Retrieves artist info xml file from last.fm, extracts biography and constructs a string from it
	public String getAlbumInfoString(String artist, String album) {
		String result = "";
		try {
			DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
			String xml_uri = "http://ws.audioscrobbler.com/2.0/?method=album.getinfo&artist=" + artist + "&album=" + album + "&api_key=1798ac371aad9cf8faef329514d55820";
			Document xml_file = docBuilder.parse(xml_uri);
			
			xml_file.getDocumentElement().normalize();
			
			NodeList wiki = xml_file.getElementsByTagName("wiki").item(0).getChildNodes();
			for(int i=0; i<wiki.getLength() ; i++) {
				if(wiki.item(i).getNodeName()=="content") 
					result = wiki.item(i).getTextContent();
			}
			result = result.substring(0, result.indexOf("User-contributed text"));
		}
		catch (IOException io_error) {
			result = "Unable to retrieve any information about this album\n";
		}
		catch (SAXParseException err) {
			System.out.println("** Parsing error" + ", line " + err.getLineNumber() + ", uri " + err.getSystemId());
			System.out.println(" " + err.getMessage());
		}
		catch (SAXException e) {
			Exception x = e.getException();
			((x==null) ? e : x).printStackTrace();
		}
		catch (Throwable t) {
			t.printStackTrace();
		}
		
		result = CleanupText(result);
		return result;
	}//end of getAlbumInfoString
	
	//Retrieves album info as a string and puts it inside a JTextArea
	public JTextArea getAlbumInfo(String artist, String album) {
		JTextArea textArea = new JTextArea(30, 50);
		textArea.setEditable(false);
		textArea.append(getAlbumInfoString(artist, album));
		
		return textArea;
	}//end of getAlbumInfo

	
	
	
	
	
	//Retrieves the artwork for the album as a BufferedImage
	public BufferedImage getAlbumArt(String artist, String album) {
		try {
			String path = getAlbumArtPath(artist, album);
			System.out.println("Path: " + path);
			if(path!="") {
				BufferedImage art = ImageIO.read(new URL(path));
				return art;
			}
		}
		catch(IOException e) {
		}
		System.out.println("unable to retrieve album art");
		return null;
	}//end of getAlbumArt
}
